package org.keshe.gui;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.stage.Stage;
import org.keshe.controllers.LogOn;
import org.keshe.user.User;

import java.io.IOException;

public class Main extends Application {

    public static Stage logOnStage;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage logOnStage) throws IOException {
        Main.logOnStage = logOnStage;
        System.out.println("连接数据库中。。。");
        if (!User.getConnection()) {
            System.err.println("数据库连接失败");
            Alert alert = new Alert(Alert.AlertType.ERROR, "无法连接到数据库", ButtonType.CLOSE);
            Button button = (Button) alert.getDialogPane().lookupButton(ButtonType.CLOSE);
            button.setOnAction(event -> Platform.exit());
            alert.show();
        } else {
            System.out.println("数据库连接成功");
            FXMLLoader fxmlLoader = new FXMLLoader(LogOn.class.getResource("LogOn.fxml"));
            Scene scene = new Scene(fxmlLoader.load());
            logOnStage.setScene(scene);
            logOnStage.setTitle("学生宿舍管理系统 — 登录");
            logOnStage.setResizable(false);
            logOnStage.show();
        }
    }

    @Override
    public void stop() throws Exception {
        System.out.println("关闭连接。。。");
        User.closeConnection();
    }
}
